#include "myserialport.h"

MySerialPort::MySerialPort(QString portName,const CSerialPortSettings & setting,QObject *parent)
    : QObject{parent}
{
    _sp=new CSerialPort();
    _sp->init(portName.toStdString(),setting);
}

MySerialPort::~MySerialPort()
{
    if(_sp)
    {
        if(_sp->isOpened()) _sp->close();
        delete _sp;
    }

//    if(_fd)
//    {
//        if(_fd->isOpen()) _fd->close();
//        _fd->deleteLater();
//    }


}

int MySerialPort::init()
{
    if(!_sp->open())
    {
            QString str=QString::fromStdString(_sp->getLastErrorString());
            qDebug()<<str;
            return -1;
    }
    else
    {
         //_fd=new QFile(GPIO_485);
         _sp->readReady.connect(this, &MySerialPort::onReceive);
    }
    return 0;
}


void MySerialPort::onReceive()
{

    int iRet = -1;
    char * str = NULL;
    str = new char[512];

    iRet = _sp->readAllData(str);
    if(iRet!=-1)
    {

        QByteArray bytes(str);
        emit sgReceive(bytes);
    }
    if(str)
    {
        delete[] str;
        str = NULL;
    }
}

int MySerialPort::sendData(const QByteArray& buf)
{
    if(!_sp) return -1;
    qDebug()<<"MySerialPort::sendData:"<<buf;
    return _sp->writeData(buf.constData(),buf.length());
}





